package com.company.jrlz.web.screens.assembleworkorderrecords;

import com.haulmont.cuba.gui.Notifications;
import com.haulmont.cuba.gui.screen.*;
import com.company.jrlz.entity.AssembleWorkOrderRecords;

import javax.inject.Inject;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

@UiController("jrlz_AssembleWorkOrderRecords.edit")
@UiDescriptor("assemble-work-order-records-edit.xml")
@EditedEntityContainer("assembleWorkOrderRecordsDc")
@LoadDataBeforeShow
public class AssembleWorkOrderRecordsEdit extends StandardEditor<AssembleWorkOrderRecords> {
    @Inject
    private Notifications notifications;


    @Subscribe
    public void onBeforeCommitChanges(BeforeCommitChangesEvent event) {
        String timeFormat = "yyyy-MM-dd HH:mm";
        if(getEditedEntity().getStartTime()!=null){
            boolean isValid1 = isValidDate(getEditedEntity().getStartTime(), timeFormat);
            if(!isValid1){
                notifications.create().withCaption("开始时间格式不正确！").show();
                event.preventCommit();
                return;
            }
        }
        if(getEditedEntity().getEndTime()!=null){
            boolean isValid2 = isValidDate(getEditedEntity().getEndTime(), timeFormat);
            if(!isValid2){
                notifications.create().withCaption("结束时间格式不正确！").show();
                event.preventCommit();
                return;
            }
        }
        if(getEditedEntity().getOrderSendTime()!=null){
            boolean isValid3 = isValidDate(getEditedEntity().getOrderSendTime(), timeFormat);
            if(!isValid3){
                notifications.create().withCaption("工单下发时间格式不正确！").show();
                event.preventCommit();
            }
        }
    }

    public boolean isValidDate(String dateStr, String format) {
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern(format); // 创建日期格式化对象
        try {
            LocalDate.parse(dateStr, dtf); // 尝试解析
            return true; // 如果解析成功，返回true
        } catch (DateTimeParseException e) {
            return false; // 如果解析抛出异常，返回false
        }
    }
}